package com.ts.service.impl;

import com.qf.utils.GsonUtils;
import com.qf.vo.Goods;
import com.ts.service.ISearchGoodsService;
import com.ts.vo.SearchGoodsParam;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SearchGoodsServiceImpl implements ISearchGoodsService {

    private String indexName = "2102-shop-goods-index";
    private String typeName = "2102-shop-goods-type";

    @Autowired
    private RestHighLevelClient client;


    @Override
    public void addGoods(Goods goods) throws Exception {

        IndexRequest request = new IndexRequest(indexName, typeName);

        request.source(GsonUtils.toJSON(goods), XContentType.JSON);

        IndexResponse index = client.index(request, RequestOptions.DEFAULT);

        System.out.println(indexName);
    }

    @Override
    public List<Goods> search(SearchGoodsParam param) throws IOException {

        List<Goods> list = new ArrayList<>();

        // 1.创建请求
        SearchRequest request = new SearchRequest();

        // 2.设置索引和类型
        request.indices(indexName).types(typeName);

        // 3.设置查询条件,高亮，排序
        SearchSourceBuilder sourceBuilder = SearchSourceBuilder.searchSource();

        // 设置开启高亮显示
        HighlightBuilder highlight = new HighlightBuilder();
        highlight.field("gname");
        highlight.preTags("<font color ='red'>");
        highlight.postTags("</font>");
        highlight.fragmentSize(50);
        sourceBuilder.highlighter(highlight);

        // 添加排序规则
        if (param.getOrderFiled() != null) {
            switch (param.getOrderFiled()) {
                case 1:
                    sourceBuilder.sort("id", SortOrder.DESC);
                    break;
                case 2:
                    sourceBuilder.sort("gprice", SortOrder.DESC);
                    break;
                case 3:
                    sourceBuilder.sort("gtypePid", SortOrder.DESC);
                    break;
            }
        }
        // 把排序规则设置给rquest对象
        request.source(sourceBuilder);

        if (!StringUtils.isEmpty(param.getKeyword())) {
            // 按照关键字搜索
            request.source().query(QueryBuilders.multiMatchQuery(param.getKeyword(), "gname", "gdesc"));
        }
        if (param.getType() != null) {
            // 按照了类型搜索
            request.source().query(QueryBuilders.termQuery("gtypeCid", param.getType()));
        }

        // 4.查询es，得到结果
        SearchResponse search = client.search(request, RequestOptions.DEFAULT);

        // 5.把JSON转成Goods封装
        SearchHit[] hits = search.getHits().getHits();
        Goods goods = null;
        for (int i = 0; i < hits.length; i++) {
            SearchHit hit = hits[i];
            // 获取一条JSON数据都应该对应一个goods对象
            Map<String, Object> sourceAsMap = hit.getSourceAsMap();
            goods = new Goods();
            try {
                BeanUtils.populate(goods, sourceAsMap);

                // 判断当前数据是否存在高亮
                HighlightField gname = hit.getHighlightFields().get("gname");
                if (gname != null) {
                    String s = gname.getFragments()[0].toString();
                    goods.setGname(s);
                }
                list.add(goods);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
        }
        return list;
    }

    public static void main(String[] args) throws InvocationTargetException, IllegalAccessException {

        Map<String, Object> map = new HashMap<>();
        map.put("gname", "abc");
        Goods goods = new Goods();
        BeanUtils.populate(goods, map);
        System.out.println(goods);
    }
}
